package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;



    @Override
    public ResponseResult upload(MultipartFile file) {
        //1.校验
        if(file==null || file.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传到minio
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = file.getOriginalFilename(); //文件原始名称
        int index = originalFilename.indexOf(".");//文件名称中 点 对应的下标
        if(index>0){
            fileName += originalFilename.substring(index);
        }

        String uploadImgFile =null;
        try {
            uploadImgFile = fileStorageService.uploadImgFile("", fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }

        //3.保存db
        try{
            WmMaterial material = new WmMaterial();
            material.setIsCollection((short)0);
            material.setType((short)0);
            material.setCreatedTime(new Date());
            material.setUrl(uploadImgFile);
            material.setUserId(WmThreadLocalUtil.getUser().getId());//由于拦截器已经将userid放入threadlocal
            save(material);

            //4.返回
            return ResponseResult.okResult(material);
        }catch (Exception e){
            //保存失败，删除图片
            if(uploadImgFile != null){
                fileStorageService.delete(uploadImgFile);
            }
            throw e;
        }
    }

    @Override
    public ResponseResult query(WmMaterialDto dto) {
        //1.校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();


        //2.分页条件查询
        IPage<WmMaterial> pageParm = new Page<>(dto.getPage(), dto.getSize());//分页对象
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //如果前端传了 且值是1  则拼条件  否则不加下面条件 代表查询所有
        if(dto.getIsCollection()!=null && dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //只能查询当前用户的素材
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        //按上传时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> page = page(pageParm, wrapper);


        //3.封装结果返回
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int)page.getTotal() );
        result.setData(page.getRecords());
        return result;
    }
}
